﻿
namespace DAPNet
{
    class ClickJoiner : IClickDeterminator
    {
        private int parameter;


        internal ClickJoiner(int parameter)
        {
            this.parameter = parameter;
        }

        internal int Parameter
        {
            get 
            {
                return parameter; 
            }
            set 
            { 
                parameter = value; 
            }
        }

        public void Determinate(ClickDetection detection)
        {
            int lastPositiveIndex = GetFirstPositiveIndex(detection);
            for (int i = lastPositiveIndex; i < detection.Count; i++)
            {
                if (detection[i])
                {
                    int gap = i - lastPositiveIndex;
                    if (gap <= parameter)
                    {
                        SetPositives(detection, lastPositiveIndex, i); 
                    }
                    lastPositiveIndex = i;
                }
            }
        }

        private int GetFirstPositiveIndex(ClickDetection detection)
        {
            for (int i = 0; i < detection.Count; i++)
            {
                if (detection[i])
                {
                    return i;
                }
            }
            return detection.Count;
        }

        private void SetPositives(ClickDetection detection, int startIndex, int endIndex)
        {
            for (int i = startIndex; i <= endIndex; i++)
            {
                detection[i] = true;
            }
        }
    }
}
